import pygame
from animation import Hitbox

def saveBoxData(charName, char):
	outDict = {}
	for key, val in char.animations.items():
		outDict[key] = val.hitboxFrames
	f = open(charName + ".boxes", "w")
	f.write(str(outDict))
	f.close()

def loadBoxData(charName, char):
	try:
		f = open(charName + ".boxes", "r")
	except:
		pass
	inDict = eval(f.read())
	f.close()
	for key, val in inDict.items():
		char.animations[key].setHitboxFrames(val)

def rectTest(a,b):
	a = pygame.Rect(a)
	b = pygame.Rect(b)
	a.normalize()
	b.normalize()
	return a.colliderect(b)

def solveCollision(objs):
	for oa in objs:
		for ob in objs:
			if oa is not ob:
				boxesa = oa.getAbsBoxFrame()
				boxesb = ob.getAbsBoxFrame()
				for ab in boxesa:
					for bb in boxesb:
						if ab.properties["type"] == 0 and bb.properties["type"] == 0:  #collision
							result = rectTest(ab.rect,bb.rect)
							if result:
								if(oa.x > ob.x):
									oa.x += 2
									ob.x -= 2
								else:
									oa.x -= 2
									ob.x += 2
						if ab.properties["type"] == 1 and bb.properties["type"] == 0: #hit
							result = rectTest(ab.rect,bb.rect)
							if result and not oa.attackAlreadyHit:
								ob.getHit(oa, ab)
								oa.hit(ob)
								oa.attackAlreadyHit = True
